package com.dengqi.mymodule.activity.update;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

import java.io.File;

import static android.content.Context.MODE_PRIVATE;

public class InstallApkReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)){
            String apk = intent.getDataString();
            if(apk.equals(context.getPackageName())){
                deleteFile(context);
                Toast.makeText(context, "自己的应用被添加了", Toast.LENGTH_LONG).show();
            }else{
                deleteFile(context);
                Toast.makeText(context, apk+"被添加了", Toast.LENGTH_LONG).show();
            }
        }else if(intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)){
        }else if(intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)){
        }
    }

    private void deleteFile(Context mContext) {
        //外部公有
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("download", MODE_PRIVATE);
        String apk_path = sharedPreferences.getString("apk_path", "");
        Long apk_id = sharedPreferences.getLong("apk_id", -1);
        File file = new File(apk_path);
        if(file.exists()){
            file.delete();
        }
        //外部私有
        File file2 = new File(mContext.getApplicationContext().getExternalFilesDir("update"), "update.jpg");
        if(file2.exists()){
            file2.delete();
        }
    }


}